package service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

import javax.sound.midi.Soundbank;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DemoService {

    /**
     * get请求json
     * @param url
     * @return
     */
    public String getJSON(String url){
        return HttpUtil.get(url);
    }

    /**
     * 根据json拿图片list
     * @param url
     * @return
     */
    public ArrayList<String> getImgList(String url){
        ArrayList<String> urls = new ArrayList<String>();

        String json = HttpUtil.get(url);

        //转对象
        JSONObject object = JSONUtil.parseObj(json);
        List<Map> data = (List<Map>)((JSONObject) object.get("data")).get("picArr");

        for (Map imgobj:data){
            String imgurl=imgobj.get("img").toString();
            urls.add(imgurl);
        }
        return urls;
    }

    /**
     * 保存图片从链接保存到本地
     * @return
     */
    public void saveFile(String url,String filePath) throws MalformedURLException {

        String fileName = url.split("/")[url.split("/").length-1];


        File file1 = new File(filePath +"/"+ fileName);
        if (file1.exists()){
            System.out.println("已存在跳过");
            return;
        }

        System.out.println ("正在下载...保存到："+filePath +"/"+ fileName);

        File file=new File(filePath);
        //判断文件夹是否存在
        if (!file.exists())
        {
            //如果文件夹不存在，则创建新的的文件夹
            file.mkdirs();
        }
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try
        {
            // 建立链接
            URL httpUrl=new URL(url);
            conn=(HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单，默认get方式
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream=conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            //判断文件的保存路径后面是否以/结尾
            if (!filePath.endsWith("/")) {

                filePath += "/";

            }
            //写入到文件（注意文件保存路径的后面一定要加上文件的名称）
            fileOut = new FileOutputStream(filePath+fileName);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            //保存文件
            while(length != -1)
            {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            conn.disconnect();
        } catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("抛出异常！！");
        }


    }

}
